<template>
  <div>
    <selectlist @nowselectbutton="nowselectbutton" />
    <div class="BtnSlot-box">
      <div class="BtnSlot-item">
        <el-button v-if="!authDisabled" class="selectAlls" @click="selectAll">
          全选
        </el-button>
        <el-button v-if="!authDisabled" class="selectAllsd" @click="selectAlld">
          选择所有可查看功能
        </el-button>
        <el-button v-if="!authDisabled" class="cancelSelectAlls" @click="cancelSelectAlls">
          取消全选
        </el-button>
      </div>
      <el-button v-if="!authDisabled" class="cancelSelectAlls" @click="save">
        保 存
      </el-button>
      <!-- <BtnSlot v-if="!authDisabled" :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot> -->
    </div>
    <el-tree class="selectTree" ref="tree" :props="treerule" :data="treeData" show-checkbox node-key="functionNo"
      accordion :check-strictly="true" :default-checked-keys="defaultchecklist" @node-click="handleEdit"
      @check="handleSionChange" @check-change="handleSelectionChange" />
  </div>
</template>

<script>
import BtnSlot from "@/components/BtnSlot";
import BaseMainSlot from "@/components_yy/BaseMainSlot/kong.vue";
import selectlist from "./selectlist.vue";
import { mymixin } from "@/utils/mixins";
// import zhrequest from "@/api/axios";
import Axios from "axios";
import $baseUrl from "@/utils/baseURL";
import store from "@/store";
import { getToken } from "@/utils/auth";
export default {
  components: {
    BaseMainSlot,
    BtnSlot,
    selectlist,
  },
  mixins: [mymixin],
  props: {
    roleNo: {
      type: String,
      default: "",
    },
    rolestu: {
      type: String,
      default: "",
    },
    authDisabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      btnList: ["save"],
      treerule: {
        children: "childList",
        label: "functionName",
      },
      treeData: [],
      treeDatas: [],
      treeDatad: [],
      defaultchecklist: [],
      functionNos: [],
      userRouteMapperId: null,
      saveActive: true,
      cancelActive: false,
      virtualSystemNo: "",
    };
  },
  watch: {
    id() {
      this.getfuncauth();
    },
    rolestu: {
      handler(Val) {
        if (Val === "add") {
          this.save();
        }
      },
    },
  },
  mounted() {
    // this.getdatamet()
  },
  // created() {
  //   this.getdatamet()
  // },
  methods: {
    getBtnEvent(flag) {
      console.log(flag);
      if (flag == "save") {
        this.save();
      }
    },
    nowselectbutton(e) {
      this.virtualSystemNo = e.virtualSystemNo;
      this.getdatamet(e);
    },
    getdatamet(e) {
      let menuurlone = $baseUrl.agricultureServiceUrl + "v3/authority/v1/function/getSystemFunction";
      Axios({
        method: "get",
        url: menuurlone,
        headers: {
          accessToken:
            store.getters.token ||
            sessionStorage.getItem("token") ||
            getToken(),
          databaseName: sessionStorage.databaseName,
          organizationList: sessionStorage.organizationList,
          organizationNo: sessionStorage.organizationNo,
          virtualSystemNo: e.virtualSystemNo,
          lesseeNo: sessionStorage.lesseeNo,
        },
      }).then((res) => {
        this.treeData = res.data.data || [];
        this.getfuncauth(e);
        this.treeDatas = [];
        this.treeDatad = [];
        this.gettreeList([...this.treeData]);
        this.gettreeListd([...this.treeData]);
      });
    },
    setTreeDisabled(list) {
      list.map((el) => {
        el.disabled = true;
        el.childList && this.setTreeDisabled(el.childList);
      });
    },
    gettreeList(e) {
      let list = JSON.parse(JSON.stringify(e));
      for (let i = 0; list.length > i; i++) {
        this.treeDatas.push(list[i]);
        if (list[i].childList && list[i].childList.length > 0) {
          this.gettreeList([...list[i].childList]);
          delete list[i].childList;
        }
      }
      // console.log(this.treeDatas)
    },
    gettreeListd(e) {
      let list = JSON.parse(JSON.stringify(e));
      for (let i = 0; list.length > i; i++) {
        this.treeDatad.push(list[i]);
        if (list[i].level === 1) {
          if (list[i].childList && list[i].childList.length > 0) {
            this.gettreeListd([...list[i].childList]);
            delete list[i].childList;
          }
        }
      }
      // console.log(this.treeDatas)
    },
    // 获取所拥有的权限
    getfuncauth(e) {
      this.defaultchecklist = [];
      let menuurlone =
        $baseUrl.agricultureServiceUrl +
        `v3/authority/v1/function/getRoleFunction?roleNo=${this.roleNo}&virtualSystemNo=${this.virtualSystemNo}`;
      // console.log(this.userid)
      Axios({
        method: "get",
        url: menuurlone,
        headers: {
          accessToken:
            store.getters.token ||
            sessionStorage.getItem("token") ||
            getToken(),
          databaseName: sessionStorage.databaseName,
          organizationList: sessionStorage.organizationList,
          organizationNo: sessionStorage.organizationNo,
          virtualSystemNo: e.virtualSystemNo,
          lesseeNo: sessionStorage.lesseeNo,
        },
      }).then((res) => {
        let PermissionList = res.data.data;
        // 查看权限下仅展示分配的权限
        if (this.authDisabled) {
          let perIdList = PermissionList.map((el) => {
            return el.functionId;
          });
          let treeData = [],
            others = [];
          this.treeData.map((el) => {
            if (perIdList.includes(el.functionId)) {
              treeData.push(el);
            } else {
              others.push(el);
            }
          });
          others.map((el) => {
            let hasPer = false,
              elObj = {};
            console.log(el);
            el.childList &&
              el.childList.map((ele) => {
                if (perIdList.includes(ele.functionId)) {
                  hasPer = true;
                  if (Object.keys(elObj).length == 0) {
                    elObj = { ...ele };
                    elObj.childList = [];
                  }
                  elObj.childList.push(ele);
                }
              });
            hasPer && treeData.push(elObj);
          });
          this.treeData = treeData;
          this.setTreeDisabled(this.treeData);
        }
        let that = this;
        that.$nextTick(() => {
          that.$refs.tree.setCheckedNodes([]);
        });
        PermissionList.forEach((item) => {
          that.$nextTick(() => {
            // 设置某个节点
            that.$refs.tree.setChecked(item.functionNo, true);
          });
        });
        // this.checklist = nowcheck
        if (res.data) {
          this.userRouteMapperId = "007";
        }
      });
    },
    selectAll() {
      // this.flag = true;
      let that = this;
      that.$nextTick(() => {
        this.$refs.tree.setCheckedNodes(this.treeDatas);
      });
      this.handleSionChange();
    },
    selectAlld() {
      // this.flag = true;
      let that = this;
      that.$nextTick(() => {
        this.$refs.tree.setCheckedNodes(this.treeDatad);
      });
      this.handleSionChange();
    },
    cancelSelectAlls() {
      let that = this;
      that.$nextTick(() => {
        that.$refs.tree.setCheckedNodes([]);
      });
    },
    handleEdit(row) {
      // console.log(row)
    },
    handleSionChange() {
      this.saveActive = true;
      this.cancelActive = true;
    },
    handleSelectionChange() {
      let list = this.$refs.tree
        .getCheckedKeys()
        .concat(this.$refs.tree.getHalfCheckedKeys());
      // console.log(list)
      this.functionNos = list;
      // console.log(list)
      // if (this.handleSelectionChange) {
      // }
    },
    // 取消
    cancel() {
      this.canInput = false;
      this.addActive = false;
      this.delActive = false;
      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false;
      // let that = this
      // this.getfuncauth()
      // that.$nextTick(
      //   () => {
      //     that.$refs.tree.setCheckedNodes([])
      //   }
      // )
    },
    save() {
      // let par = {
      //   roleNo: this.roleNo,
      //   functionNos: this.functionNos
      // }
      let menuurlone =
        $baseUrl.agricultureServiceUrl + `v3/authority/v1/role/bindFunction`;
      // console.log(this.userid)
      Axios({
        method: "post",
        url: menuurlone,
        headers: {
          accessToken:
            store.getters.token ||
            sessionStorage.getItem("token") ||
            getToken(),
          databaseName: sessionStorage.databaseName,
          organizationList: sessionStorage.organizationList,
          organizationNo: sessionStorage.organizationNo,
          virtualSystemNo: this.virtualSystemNo,
          lesseeNo: sessionStorage.lesseeNo,
        },
        data: `roleNo=${this.roleNo}&functionNos=${this.functionNos}&virtualSystemNo=${this.virtualSystemNo}`,
      }).then((res) => {
        if (res.data.code === 1) {
          this.$message.success(res.data.msg || "修改成功！");
          // this.getfuncauth()
          this.$emit("roles", "");
          this.cancel();
        } else {
          this.$message.error(res.data.msg || "修改失败！");
        }
      });
      // roleManage.addfuncauth(`roleNo=${this.roleNo}&functionNos=${this.functionNos}`).then(res => {
      //   if (res.code === 1) {
      //     this.$message.success(res.msg || "修改成功！");
      //     // this.getfuncauth()
      //     this.$emit('roles', '')
      //     this.cancel()
      //   } else {
      //     this.$message.error(res.msg || "修改失败！");
      //   }
      // })
      // console.log("设置权限")
    },
  },
};
</script>
<style lang="scss" scoped>
.BtnSlot-box {
  display: flex;
  justify-content: space-between;
  margin: 5px 0;
}

.selectTree {
  max-height: 490px;
  padding: 10px;
  background-color: #fafafa;
  border: 1px solid #eaeaea;
  overflow: auto;
}
</style>
